package com.example.myapplication

import android.Manifest
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.IOException
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException
import androidx.core.net.toUri
import kotlin.concurrent.thread
import kotlin.system.exitProcess


class MainActivity : AppCompatActivity() {
//    private var fileServer: FileServer? = null

    fun tc(){
        exitProcess(0)
    }
    private lateinit var ipPortText: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ipPortText = findViewById(R.id.ip_port_text)

        if (checkPermissions()) {
            startFileServer()
            displayIpAndPort()
        } else {
            requestPermissions()
        }
    }

    private fun checkPermissions(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager()
        } else {
            val result =
                ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE)
            return result == PackageManager.PERMISSION_GRANTED
        }
    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun requestPermissions() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                var intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(("package:$packageName").toUri()); // 指定当前应用包名
                startActivityForResult(intent, PERMISSION_REQUEST_CODE);

            } catch (e: Exception) {
                val intent = Intent()
                intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                startActivityForResult(intent, PERMISSION_REQUEST_CODE)
            }
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                PERMISSION_REQUEST_CODE
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startFileServer()
                displayIpAndPort()
            } else {
                Toast.makeText(
                    this,
                    "Permissions denied. Cannot start file server.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    startFileServer()
                    displayIpAndPort()
                } else {
                    Toast.makeText(
                        this,
                        "Permissions denied. Cannot start file server.",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    private fun startFileServer() {
        try {
//            thread {
//                fileServer = FileServer()
//            }
            val serviceIntent = Intent(this, MyHttpService::class.java)

            startService(serviceIntent)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun displayIpAndPort() {
        val ipAddress = localIpAddress
        if (ipAddress != null) {
            val ipPort = "访问地址: http://$ipAddress:$PORT"
            ipPortText.text = ipPort
        } else {
            ipPortText.text = "无法获取 IP 地址"
        }
    }



    override fun onDestroy() {
        super.onDestroy()
//        if (fileServer != null) {
//            fileServer!!.stop()
//        }
    }

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1
        private const val PORT = 8080

        val localIpAddress: String?
            get() {
                try {
                    val en = NetworkInterface.getNetworkInterfaces()
                    while (en.hasMoreElements()) {
                        val intf = en.nextElement()
                        val enumIpAddr = intf.inetAddresses
                        while (enumIpAddr.hasMoreElements()) {
                            val inetAddress = enumIpAddr.nextElement()
                            if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                                return inetAddress.hostAddress
                            }
                        }
                    }
                } catch (ex: SocketException) {
                    ex.printStackTrace()
                }
                return null
            }
    }
}